using System;
using System.Collections.Generic;
using UnityEngine;

namespace Yoozoo.Gameplay.Liberty.AI
{
    public class RayCaster : PhysicsCaster
    {
        public float maxDistance = 100;
        public LayerMask layerMask;

        public bool containsTrigger = false;
        
        [SerializeField]
        private bool casted = false;
        public bool Casted => casted;

        private int castedCount = 0;
        
        private RaycastHit hitInfo;

        public override void Cast()
        {
            if (!enabled)
            {
                casted = false;
                return;
            }

            if (containsTrigger)
            {
                casted = Physics.Raycast(transform.position, transform.forward, out var hit, maxDistance, layerMask);
                if (casted)
                {
                    castedCount = 1;
                    hitInfo = hit;
                }
                else
                {
                    castedCount = 0;
                }
            }
            else
            {
                casted = false;
                castedCount = 0;
                float castDistance = maxDistance;
                Vector3 startPoint = transform.position;
                bool needCast = true;
                int castCount = 0;
                while (castDistance > 0.1f && needCast && castCount < 5)
                {
                    bool c = Physics.Raycast(startPoint, transform.forward, out var hit, castDistance, layerMask);
                    if (c && !hit.collider.isTrigger)
                    {
                        casted = true;
                        castedCount = 1;
                        hitInfo = hit;
                        break;
                    }
                    else if (c && hit.collider.isTrigger)
                    {
                        startPoint = hit.point + transform.forward * 0.05f;
                        castDistance = maxDistance - Vector3.Distance(transform.position, startPoint);
                        needCast = true;
                    }
                    else
                    {
                        needCast = false;
                    }
                    castCount++;
                }
            }
        }

        public override void SetCastDistance(float d)
        {
            maxDistance = d;
        }

#if UNITY_EDITOR

        private void OnDrawGizmosSelected()
        {
            Gizmos.color = Color.red;
            Gizmos.DrawLine(transform.position,transform.forward * maxDistance + transform.position);
        }
#endif
        public override void GetHitInfo(ref List<RaycastHit> hits)
        {
            if (Casted)
            {
                if (!hits.Contains(hitInfo))
                {
                    hits.Add(hitInfo);
                }
            }
        }
    }
}